<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .switch {
            height: 100px;
            width: 200px;
            background: #1890ff;
            border-radius: 50px;
            padding: 8px;
            box-sizing: border-box;
        }
        .switch.off {
            background: #ccc;
        }
        /* 按钮在右侧的样式 */
        .switch .btn {
            height: 84px;
            width: 84px;
            background: #fff;
            border-radius: 42px;
            float: right;
            transition: transform .3s ease, width .3s ease;
        }
        /* 按钮在左侧的样式 */
        .switch .btn.off {
            transform: translateX(-100px);
        }

        /* 鼠标按下时的.switch .btn */
        .switch:active .btn {
            width: 100px;
        }

        .switch:active .btn.off {
            transform: translateX(-84px);
        }

    </style>
</head>
<body>
    <div class="switch">
        <div class="btn"></div>
    </div>

    <script>

        const switchWrapper = document.querySelector('.switch');
        const switchBtn = document.querySelector('.switch .btn');
        let isOn = true;

        switchWrapper.addEventListener('click', function () {
            // 点击干啥
            // if (isOn) {
            //     switchBtn.setAttribute('class', 'btn off');
            //     switchWrapper.setAttribute('class', 'switch off');
            // } else {
            //     switchBtn.setAttribute('class', 'btn');
            //     switchWrapper.setAttribute('class', 'switch');
            // }
            switchBtn.setAttribute('class', 'btn ' + (isOn ? 'off' : ''));
            switchWrapper.setAttribute('class', 'switch ' + (isOn ? 'off' : ''));
            isOn = !isOn;
        });
    </script>
</body>
</html>